<?php
// +----------------------------------------------------------------------
// | Description: 用户
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

use think\Db;
use think\Cache;
use app\admin\model\Common;
use com\verify\HonrayVerify;
use PHPExcel;
use common\Utils;
use app\common\model\paymentOrder;
use app\admin\model\PaymentOrder as PO;
class Myloans extends Common
{

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如微信模块用weixin作为数据表前缀
     */
    protected $name = 'apply';
    protected $createTime = 'time';
    protected $updateTime = false;
    protected $autoWriteTimestamp = DATETIME;

    const PAY_MODE_OFFLINE = 1; // 线下人工打款
    const PAY_MODE_ONLINE = 2; // 线上富有打款

    // protected $insert = [
    //     'status' => 1,
    // ];


    /**
     * [getDataList 列表]
     * @DateTime  2017-08-8
     * @param     [string]                   $keywords [关键字]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [t每页数量]
     * @return    [array]                             [description]
     */
    public function getDataList($keywords, $page, $limit, $valuedate, $os = '', $status = "",$type)
    {

        $map = [];
        if ($valuedate) {
            $valuedate = substr($valuedate, 0, 10);
            $valuedate = date('Y-m-d', strtotime("$valuedate +1 day"));
            $map['fk_time'] = ['like', '%' . $valuedate . '%']; //放款列表 筛选放款时间
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%' . $keywords . '%'];
        }
        if ($os) {
            $map['os'] = $os;
        }

        $map['status'] = array('in', '3, 4, 5, 12');


        //财务改动 线下放款未处理显示回访通过
        if(config('PAY_MODE') == self::PAY_MODE_OFFLINE){
            if($type !== '已放款'){
                $map['status'] = array('in', '9');
            }
        }

        $admin_id = $GLOBALS['userInfo']['id'];
        if ($admin_id != 1) {
            $map['treasurer'] = $admin_id;
        }else{
            $map['treasurer'] = ['exp','is not null'];
        }

        //财务改动 不显示回访通过
        if (in_array($status, [3, 4, 5, 12])) {
            $map['status'] = $status;
        }

        $dataCount = $this->where($map)->count('id');

        $list = $this
            ->where($map);
        // 若有分页
        if ($page && $limit) {
            $list = $this->page($page, $limit);
        }

        $list = $this
            // ->field('id,status,time,money,period,order_number,check_time,check_aid,check2_aid,check2_time,name,credit_rate,service_rate,procedure_rate,appoint_time,uid,treasurer,monepassdate,merchandiser,phone,hang,id_card')
            ->order(array('status = 9' => 'desc','auth_type'=>'desc', 'status = 3' => 'desc', 'auth_type'=>'desc','status = 4' => 'desc', 'auth_type'=>'desc','status = 5' => 'desc', 'auth_type'=>'desc','status = 11' => 'desc','auth_type'=>'desc', 'appoint_time' => 'asc', 'auth_type'=>'desc','fives_claim_date' => 'desc', 'auth_type'=>'desc','id' => 'asc','auth_type'=>'desc'))
            ->select();
        $list = modelo2array($list);
        //var_dump($list);exit;
        foreach ($list as $key => $value) {
            $map2['id'] = $value['check_aid'];
            $map1['id'] = $value['check2_aid'];
            $mapm['id'] = $value['merchandiser'];
            $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);
            $list[$key]['user_admin1'] = Db::name('admin_user')->field('username')->where($map2)->find();
            $list[$key]['user_admin1'] = str_replace('123', '', $list[$key]['user_admin1']);
            $list[$key]['user_admin2'] = Db::name('admin_user')->field('username')->where($map1)->find();
            $list[$key]['user_admin2'] = str_replace('123', '', $list[$key]['user_admin2']);
            $list[$key]['merchandiser'] = Db::name('admin_user')->field('username')->where($mapm)->find();
            $list[$key]['merchandiser'] = str_replace('123', '', $list[$key]['merchandiser']);
            $list[$key]['admin_uid'] = $admin_uid;
            $list[$key]['check_time'] = substr($value['check_time'], 0, 10);
            $list[$key]['check2_time'] = substr($value['check2_time'], 0, 10);
            $list[$key]['appoint_time'] = substr($value['appoint_time'], 0, 10);
            $list[$key]['times'] = substr($value['time'], 0, 10);
            $list[$key]['monepassdate'] = substr($value['monepassdate'], 0, 10);

            $list[$key]['already_money'] = Documentary::alreadyRepay($value, $list[$key]['status']);//已还总金额
            $list[$key]['repay'] = $this->getRepay($list[$key]['status'], $value, $list[$key]['already_money']);//应还总金额
            $list[$key]['surplus'] = $this->getSurplus( $list[$key]['repay'],$list[$key]['status'] );//剩余应还金额

            $hangss = substr($value['hang'], 0, 11);
            if ($hangss == '1tolifthang') {
                $list[$key]['hang'] = null;
            }
            $mapseq['apply_id'] = $value['id'];
            $mapseq['auth_admin'] = 3;
            $dataseq = Db::name('claim_seq')->field('seq')->where($mapseq)->find();
            if (!$dataseq) {
                $list[$key]['seq'] = '';
            } else {
                $list[$key]['seq'] = $dataseq['seq'];
            }
        }
        $data['list'] = $list;
        $data['dataCount'] = $dataCount;

        //财务改动 线上线下配置
        $data['pay_model'] = config('PAY_MODE');

        return $data;
    }

    /**
     * @param $keywords  [搜索关键词]
     * @param $page      [页码]
     * @param $limit     [每页数]
     * @param $condition [筛选条件] //SUCCESS  OR FAILURE
     * @param $time      [筛选条件] // datetiem
     * @AUTHER 范俊成
     * @DATE 2018/4/4
     */
    public function get_history($keywords,$page,$limit,$time='',$condition='')
    {
//        $time='2018-04-02T16:00:00.000Z';
        $start = empty($time)?'': date('Y-m-d H:i:s',strtotime($time));
        $end   = empty($time)?'':date('Y-m-d H:i:s',strtotime($time)+24*60*60);
        $admin_id   =   $GLOBALS['userInfo']['id'];
        $offset = $page==1?0:($page-1)*$limit;

        $sql=' select p.result_pay,a.time,p.type,p.update_time,a.name,a.phone,p.reason,u.username,a.loan_out_money from qh_apply a inner join qh_payment_order p on a.order_number=p.apply_id inner join qh_admin_user u  on a.treasurer=u.id';
        $sql1='select count(*) from qh_apply a inner join qh_payment_order p on a.order_number=p.apply_id  inner join qh_admin_user u  on a.treasurer=u.id ';
        if(preg_match('/^\d{11}$/',$keywords)){
            $sql=$sql.' where  a.phone='.$keywords;   //如果是11位纯数字就是手机号
            $sql1=$sql1.' where  a.phone='.$keywords;   //如果是11位纯数字就是手机号
        }elseif(preg_match('/^\d{16}$/',$keywords)){
            $sql=$sql.' where  a.order_number='.$keywords;//如果是16位纯数字就是订单号
            $sql1=$sql1.' where  a.order_number='.$keywords;//如果是16位纯数字就是订单号
        }elseif($keywords==''){
            $sql=$sql;                                      //如果是空就是没有条件
        }else{
            $sql=$sql." where  a.name='$keywords'";   //剩下的就是默认是按姓名查找
            $sql1=$sql1." where  a.name='$keywords'";   //剩下的就是默认是按姓名查找
        }

        if(!empty($time)){
            if(strpos($sql,'where')){
                $sql=$sql." and p.update_time between '$start' and '$end'  ";
                $sql1=$sql1." and p.update_time between '$start' and '$end'  ";
            }else{
                $sql=$sql."  where p.update_time between '$start' and '$end'  " ;
                $sql1=$sql1."  where p.update_time between '$start' and '$end'  " ;
            }
        }
        if(!empty($condition)){
            if(strpos($sql,'where')){
                $sql = $sql." and p.result_pay='$condition' ";
                $sql1 = $sql1." and p.result_pay='$condition' ";
            }else{
                $sql = $sql." where p.result_pay='$condition' ";
                $sql1 = $sql1."  where p.result_pay='$condition' ";
            }
        }
//        $admin_id=1;
        if($admin_id == 1){

            $sql=$sql.'  order by p.update_time desc limit '.$limit.' offset '.$offset;  //如果是管理员就默认可以看到全部
            $sql1=$sql1.'  order by p.update_time desc ';  //如果是管理员就默认可以看到全部
        }else{
            if(strpos($sql,'where')){
                $sql=$sql.'  and a.treasurer='.$admin_id.' order by p.update_time desc limit '.$limit.' offset '.$offset;  //否则只能看到自己的
                $sql1=$sql1.'  and a.treasurer='.$admin_id.' order by p.update_time desc  ';  //否则只能看到自己的
            }else{
                $sql=$sql.'   where  a.treasurer='.$admin_id.' order by p.update_time desc limit '.$limit.' offset '.$offset;  //否则只能看到自己的
                $sql1=$sql1.'  where a.treasurer='.$admin_id.' order by p.update_time desc  ';  //否则只能看到自己的
            }

        }
//       echo $sql;exit;
//        echo $sql1;exit;

        $result = $this->query($sql);  #三表联查有待优化
        $count  = $this->query($sql1);
//        var_dump($result);exit;
//        var_dump($count);exit;
        $result['list']=$result;
        $result['dataCount']=$count[0]['count(*)'];
        return $result;

    }











    public function getDataListExcel($keywords, $page, $limit, $valuedate, $os = '', $status = "")
    {
        $map = [];
        if ($valuedate) {
            $valuedate = substr($valuedate, 0, 10);
            $valuedate = date('Y-m-d', strtotime("$valuedate +1 day"));
            $map['time'] = ['like', '%' . $valuedate . '%'];
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%' . $keywords . '%'];
        }
        if ($os) {
            $map['os'] = $os;
        }

        $admin_id = $GLOBALS['userInfo']['id'];
        if ($admin_id == 1) {
            $map['status'] = array('in', '9,3,5,4,11,12');
        } else {
            $map['status'] = array('in', '9,3,5,4,11,12');
            $map['treasurer'] = $admin_id;
        }

        if (in_array($status, [3, 4, 5, 9, 11, 12])) {
            $map['status'] = $status;
        }

        $dataCount = $this->where($map)->count('id');

        $list = $this
            ->where($map);


        if ($page && $limit && !($keywords || $valuedate || $os || $status)) { // 若有分页 且赛选条件不为空
            $list = $this->page($page, $limit);
        }


        $list = $this
//            ->field('status,id,time,name,money,period,phone,check_time,check2_time,monepassdate,appoint_time,mobile_type,check_aid,check2_aid,merchandiser')
            ->order(array('status = 9' => 'desc', 'status = 3' => 'desc', 'status = 4' => 'desc', 'status = 5' => 'desc', 'status = 11' => 'desc', 'appoint_time' => 'asc', 'fives_claim_date' => 'desc', 'id' => 'asc'))
            ->select();

        foreach ($list as $key => $value) {
            $map2['id'] = $value['check_aid'];
            $map1['id'] = $value['check2_aid'];
            $mapm['id'] = $value['merchandiser'];
            $list[$key]['status'] = $this->setOverdue($value['id'], $value['appoint_time'], $value['status']);
            $list[$key]['user_admin1'] = Db::name('admin_user')->field('username')->where($map2)->value('username');
            $list[$key]['user_admin1'] = str_replace('123', '', $list[$key]['user_admin1']);
            $list[$key]['user_admin2'] = Db::name('admin_user')->field('username')->where($map1)->value('username');
            $list[$key]['user_admin2'] = str_replace('123', '', $list[$key]['user_admin2']);
            $list[$key]['merchandiser'] = Db::name('admin_user')->field('username')->where($mapm)->value('username');
            $list[$key]['merchandiser'] = str_replace('123', '', $list[$key]['merchandiser']);
            $list[$key]['admin_uid'] = $admin_uid;
            $list[$key]['check_time'] = substr($value['check_time'], 0, 10);
            $list[$key]['check2_time'] = substr($value['check2_time'], 0, 10);
            $list[$key]['appoint_time'] = substr($value['appoint_time'], 0, 10);
            $list[$key]['times'] = substr($value['time'], 0, 10);
            $list[$key]['monepassdate'] = substr($value['monepassdate'], 0, 10);
            $list[$key]['status']=$this->statusInfo($list[$key]['status']);
//            $hangss = substr($value['hang'], 0, 11);
//            if ($hangss == '1tolifthang') {
//                $list[$key]['hang'] = null;
//            }
            $mapseq['apply_id'] = $value['id'];
            $mapseq['auth_admin'] = 3;
            $dataseq = Db::name('claim_seq')->field('seq')->where($mapseq)->find();
            if (!$dataseq) {
                $list[$key]['seq'] = '';
            } else {
                $list[$key]['seq'] = $dataseq['seq'];
            }

            #银行卡号导出成字符串
            $list[$key]['bank_card_number'] = "  ".$value['bank_card_number']." ";
            $list[$key]['phone'] = "  ".$value['phone']." ";
        }
        $data['list'] = $list;
        $data['dataCount'] = $dataCount;

        return $data;
    }


    // 财务放款
    public function getLoans_bak($param)
    {
        $id = $param['id'];
        $order_number = $param['order_number'];
        $uid = $param['uid'];
        $period = $param['period'];
        $map['order_number'] = $order_number;
        $admin_uid = $GLOBALS['userInfo']['id'];;
        $time = $period * 24 * 60 * 60 + time();
        $appoint_time = date("Y-m-d H:i:s", $time);
        $fk_time = date("Y-m-d H:i:s", time());
        $data = ['fk_time' => $fk_time, 'status' => 3, 'appoint_time' => $appoint_time];
        $admin_data = ['date' => $fk_time, 'status' => 1, 'apply_id' => $id, 'uid' => $uid, 'admin_user_id' => $admin_uid, 'authstatus' => 3];
        $this->startTrans();
        try {
            Db::name('admin_user_clien')->insert($admin_data);
            $info = $this->save($data, $map);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error = "确认还款失败";
            return false;
        }

    }

    // 财务放款 改动放款
    public function getLoans($param)
    {

       if(!$param['smsVerification_s'] || strlen($param['smsVerification_s']) != 4 ){
            return resultArray(["error" => '验证码错误1']);
        }
        $user_id = $GLOBALS['userInfo']['id'];
        $res = Db::name('smsverification')->where(['user_id'=>$user_id])->field('smsVerification,create_date')->find();
        if($param['smsVerification_s'] != $res['smsVerification'] || (time() > (strtotime($res['create_date'])+(config('sms_aging')['sms_aging'])))){
              return resultArray(["error" => '验证码错误2']);
        }

        $id = $param['id'];
        $order_number = $param['order_number'];
        $uid = $param['uid'];
        $period = $param['period'];
        $map['order_number'] = $order_number;

        $admin_uid = $GLOBALS['userInfo']['id'];;
        $time = $period * 24 * 60 * 60 + time();
        $appoint_time = date("Y-m-d H:i:s", $time);
        $fk_time = date("Y-m-d H:i:s", time());
        $data = ['fk_time' => $fk_time, 'status' => 3, 'appoint_time' => $appoint_time];
        $admin_data = ['date' => $fk_time, 'status' => 1, 'apply_id' => $id, 'uid' => $uid, 'admin_user_id' => $admin_uid, 'authstatus' => 3];
        $this->startTrans();



        #构造打款订单数据
        $apply_info = $this->where(["order_number"=>$order_number])->find();
        $add_data["apply_id"]       = $apply_info->order_number;      //打款申请单
        $add_data["uid"]            = $apply_info->uid;               //收款人 uid
        $add_data["total_money"]    = $apply_info->loan_out_money;    //订单金额
        $add_data["no_order"]       = date('Ymd').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $add_data["acct_name"]      = $apply_info['name'];      //收款人姓名
        $add_data["card_no"]        = $apply_info->bank_card_number;   //卡号

        $project = str_replace(['【', '】'],  ['',''], config('message_prefix'));
        $add_data["info_order"]     = $project.'线下放款';               //订单描述
        $add_data["flag_card"]      = 0;
        $add_data["create_time"]    = date("Y-m-d H:i:s",time());
        $add_data["dt_order"]       = date('YmdHis', time());
        //  修改支付订单表信息
        $add_data['update_time'] = date('Y-m-d H:i:s');
//        $add_data['oid_paybill'] = $oid_paybill;
        $add_data['money_order'] = $apply_info->loan_out_money;
        $add_data['result_pay'] = 'SUCCESS';
//        $add_data['settle_date'] = $settle_date;
        $add_data['ret_code'] = "0000";
        $add_data['ret_msg'] = "支付成功";
        $add_data['status'] = 1;
        $add_data['type'] = '1'; // 1线下 0线上

        $res = paymentOrder::create($add_data);
        if(!$res) {
            $this->error = "创建订单失败";
            return false;
        }





        try {
            Db::name('admin_user_clien')->insert($admin_data);
            $info = $this->save($data, $map);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error = "确认放款失败";
            return false;
        }

    }


    //添加借款
    public function addto($param)
    {
        $map['id'] = $param['id'];
        $info = $this->where($map)->find();
        $uid = $info['uid'];                      //用户id
        $name = $info['name'];                    //用户姓名
        $merchandiser = $info['merchandiser'];    //跟单员
        $fk_time = date('Y-m-d H:i:s', time());       //申请时间
        $status = 3;                              //已经放款
        $money = $param['money'];                 //借款金额
        $summoney = $param['summoney'];           //还款金额
        $appoint_time = $param['hk_date'];             //还款时间
        $treasurer = $GLOBALS['userInfo']['id'];      //财务员
        $appoint_time = date('Y-m-d', strtotime("$appoint_time +1 day"));  //约定还款时间
        $order_number = date('YmdHi') . rand(1000, 9999);
        $phone = $info['phone'];
        $data = ['uid' => $uid, 'name' => $name, 'fk_time' => $fk_time, 'status' => $status,
            'money' => $money, 'summoney' => $summoney, 'appoint_time' => $appoint_time,
            'phone' => $phone, 'order_number' => $order_number, 'time' => $fk_time,
            'treasurer' => $treasurer, 'merchandiser' => $merchandiser
        ];
        $info = Db::name('apply')->insert($data);
        if (!$info) {
            $this->error = '添加失败';
            return false;
        }
        return true;


    }


    /**
     * 功能:  修改约定还款时间model
     * @Author   zhanhuiping
     * @email    18702529695@163.com
     * @DateTime 2017-09-08
     * @param    [type]              $param [description]
     * @return   [type]                     [description]
     */
    public function updatedate($param)
    {
        $updatedate = $param['updatedate'];
        $descnote = $param['descnote'];
        $updatedate = date('Y-m-d H:i:s', strtotime($updatedate));
        $id = $param['id'];
        $map['id'] = $id;
        $data = ['appoint_time' => $updatedate, 'status' => 12, 'descnote' => $descnote];
        $info = $this->save($data, $map);
        if (!$info) {
            $this->error = "修改失败";
            return false;
        }
        return true;

    }

    /**
     * [getDataById 拒绝放款]
     * @linchuangbin
     * @DateTime  2017-02-10T21:16:34+0800
     * @param     string $id [主键]
     * @return    [array]
     */
    public function myloanspass($param)
    {
        $uid = $param['uid'];
        $opinion = $param['opinion'];
        $order_number = $param['order_number'];
        $id = $param['id'];
        $lendmoneydate = date('Y-m-d H:i:s', time());
        $admin_uid = $GLOBALS['userInfo']['id'];

        $map['order_number'] = $order_number;
        $data = ['status' => 11, 'refuse_to_lend_money' => $opinion, 'lendmoneydate' => $lendmoneydate];
        $admin_data = ['status' => 0, 'uid' => $uid, 'date' => $lendmoneydate,
            'admin_user_id' => $admin_uid, 'apply_id' => $id,
            'authstatus' => 3];
        Db::name('admin_user_clien')->insert($admin_data);
        $info = $this->save($data, $map);
        if (!$info) {
            return $info;
            exit;
        }
        return $info;
    }


    /**
     * [getDataById 根据主键获取详情]
     * @linchuangbin
     * @DateTime  2017-02-10T21:16:34+0800
     * @param     string $id [主键]
     * @return    [array]
     */
    public function getDataById($id = '')
    {
        $data = $this
            ->field('id,money,period,credit_rate,service_rate,procedure_rate,overdue_rate')
            ->where('id', $id)
            ->find();
        return $data;
    }

    /**
     * [createData 新建]
     * @linchuangbin
     * @DateTime  2017-02-10T21:19:06+0800
     * @param     array $param [description]
     * @return    [array]                         [description]
     */
    public function createData($param)
    {

        // // 验证
        // $validate = validate($this->name);
        // if (!$validate->check($param)) {
        //     $this->error = $validate->getError();
        //     return false;
        // }
        try {
            $this->data($param)->allowField(true)->save();
            return true;
        } catch (\Exception $e) {
            $this->error = '添加失败';
            return false;
        }
    }

    /**
     * [updateDataById 编辑]
     * @linchuangbin
     * @DateTime  2017-02-10T21:24:49+0800
     * @param     [type]                   $param [description]
     * @param     [type]                   $id    [description]
     * @return    [type]                          [description]
     */
    public function updateDataById($param, $id)
    {
        $checkData = $this->get($id);
        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }

        // // 验证
        // $validate = validate($this->name);
        // if (!$validate->check($param)) {
        //     $this->error = $validate->getError();
        //     return false;
        // }

        try {
            $this->allowField(true)->save($param, [$this->getPk() => $id]);
            return true;
        } catch (\Exception $e) {
            $this->error = '编辑失败';
            return false;
        }
    }


    //财务认领
    public function getclaim($param)
    {
        $order_number = $param['order_number'];
        $map['order_number'] = $order_number;
        $admin_uid = $GLOBALS['userInfo']['id'];
        $data = ['treasurer' => $admin_uid];
        $info = $this->save($data, $map);
        if (!$info) {
            return false;
            exit;
        }
        return true;
    }

    /*
    * auth:zhanhuiping
    * date:20170905
    */
    public function hang($param)
    {
        $map['id'] = $param['id'];
        $hang = $param['hang'] ? $param['hang'] : '';
        $data = ['hang' => $hang];

        $info = $this->save($data, $map);
        if ($info == false) {
            $this->error = '挂起失败';
            return false;
        }
        //$hangdata = $this->where($map)->field('hang')->find();
        return true;
    }

    /*
    * auth:zhanhuiping
    * date:20170905
    */
    public function tolifthang($param)
    {
        $map['id'] = $param['id'];
        $info = $this->where($map)->field('hang')->find();
        $hang = '1tolifthang' . $info['hang'];
        $data = ['hang' => $hang];
        $info = $this->save($data, $map);
        if (!$info) {
            $this->error = '挂起失败';
            return false;
        }
        $data = null;
        return $data;


    }

    /**
     *  导出Excel,返回地址
     * @author cxr <1481746137@qq.com>
     * @param $keywords
     * @param $page
     * @param $limit
     * @param $valuedate
     * @param $os
     * @param $status
     * @return string
     */
    public function export_bak($keywords, $page, $limit, $valuedate, $os, $status)
    {
        $data =  $this->getDataListExcel($keywords, $page, $limit, $valuedate, $os, $status);
        $data = modelo2array( $data['list']);
        $arrdata[] = ['排序','申请时间','姓名','状态','借款','期限','手机号码','初审员','初审时间','复审员','复审时间','M1回访员','回访时间','还款日期','机型'];
        $keys = ['seq','time','name','status','money','period','phone','user_admin1','check_time','user_admin2','check2_time','merchandiser','monepassdate','appoint_time','mobile_type'];
        $filter =  $this->filterVal($data,$keys);
        $arrdata = array_merge ($arrdata,  $filter );

        //var_dump($arrdata);exit;
        $path = $this->create_xls($arrdata,'myloans.xls');
        return $path;

    }

    /**
     *  财务改动，导出放款列表
     * @author cxr <1481746137@qq.com>
     * @param $keywords
     * @param $page
     * @param $limit
     * @param $valuedate
     * @param $os
     * @param $status
     * @return string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function export($keywords, $page, $limit, $valuedate, $os, $status)
    {
        $data =  $this->getDataListExcel($keywords, $page, $limit, $valuedate, $os, $status);
        $data = modelo2array( $data['list']);
        $arrdata[] = [date("Y年m月d日 h:i:s")];
        $arrdata[] = ['申请时间','姓名','手机号码','借款金额','状态','银行卡号','打款金额'];
        $keys = ['time','name','phone','money','status','bank_card_number','loan_out_money'];
        $filter =  $this->filterVal($data,$keys);
        $arrdata = array_merge ($arrdata,  $filter );

        //var_dump($arrdata);exit;
        $path = $this->create_xls($arrdata,'myloans.xls');
        return $path;

    }

    /**
     * 按Key过滤排序
     * @author cxr <1481746137@qq.com>
     * @param $arr
     * @param $keys
     * @return mixed
     */
    public function filterVal($arr,$keys){
        foreach($keys as $k=>$v)
            foreach($arr as $k2=>$v2)
                $new_array[$k2][$v] = $arr[$k2][$v];
        return $new_array;
    }



    /**
     * 创建财务excel
     * @author cxr <1481746137@qq.com>
     * @param $data
     * @param string $filename
     * @return string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function create_xls($data,$filename='myloans.xls'){
        ini_set('max_execution_time', '0');
        $filename=str_replace('.xls', '', $filename).'.xls';
        $phpexcel = new PHPExcel();
        $phpexcel->getProperties()
            ->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        $phpexcel->getActiveSheet()->fromArray($data);
        $phpexcel->getActiveSheet()->setTitle('Sheet1');
        $phpexcel->setActiveSheetIndex(0);
        $objwriter = \PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
        $dir = dirname(__FILE__);
        $objwriter->save(ROOT_PATH.'/public/'.$filename);
        return  '/public/'.$filename;
    }


    /**
     * 功能:    批量认领
     * @Author   Mrzhp
     * @email    18702529695@163.com
     * @DateTime 2018-01-17
     * @param    [type]              $param [description]
     * @return   [type]                     [description]
     */
    public function batchclaim($param)
    {
        $data = $param['multipleSelection'];
        $admin_uid = $GLOBALS['userInfo']['id'];

        $arr =array();
        $arruid =array();
        foreach($data as $key=>$value)
        {
            $arr[] = $value['id'];
            $arruid[] = $value['uid'];
        }

        $this->startTrans();
        try{

            $count = count($arr);
            for($i=$count-1;$i>=0;$i--)
            {
                $id = $arr[$i];
                $uid = $arruid[$i];
                $nowdate = date('Y-m-d',time());
                $mapseq['nowdate'] = ['like','%'.$nowdate.'%'];
                $infocount = Db::name('claim_seq')
                    ->where('auth_admin',4)
                    ->where('admin_id',$admin_uid)
                    ->where($mapseq)
                    ->count();
                $claim_date = ['uid'=>$uid,'apply_id'=>$id,'nowdate'=>$nowdate,'auth_admin'=>4,'seq'=>$infocount+1,'admin_id'=>$admin_uid];
                Db::name('claim_seq')->insert($claim_date);
            }

            $where['id'] = array('in',$arr);
            $fives_claim_date = date('Y-m-d H:i:s',time());
            $data = array('treasurer'=>$admin_uid,'fives_claim_date'=>$fives_claim_date);
            $info = $this->save($data,$where);
            // 提交事务
            $this->commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            $this->rollback();
            $this->error = '删除失败';
            return false;
        }
    }



    /**
     * 功能:    后台短信验证
     * @Author   Mrzhp
     * @email    18702529695@163.com
     * @DateTime 2018-05-17
     * @return   [type]              [description]
     */
    public function smsVerification($param)
    {

       $user_id = $GLOBALS['userInfo']['id'];
       
       $phone = Db::name('admin_user')->where(['id'=>$user_id])->value('phone');
       if(!$phone){
         $data = ['code'=>400,'message'=>'请绑定手机号码'];
         return $data;
       }

       $key_user_sms = 'sms'.$user_id;
       $key = Cache::get($key_user_sms);
       if($key){
         $data = ['code'=>400,'message'=>'请一分钟后发送'];
         return $data;
       }else{
          Cache::set($key_user_sms,1,60);
       }
       
       $verify = rand(1000,9999);
       $msg = config('message_prefix') . "您的验证码为：".$verify.'，5分钟内有效。';
       $res = Utils::curl_heart_verify($phone,$msg);
       if($res['status'] == 1){
         $id =  Db::name('smsverification')->where(['user_id'=>$user_id])->value('id');
         $data = [
                   'user_id' =>$user_id,
                   'phone' => $phone,
                   'smsVerification'=>$verify,
                   'create_date' =>date('Y-m-d H:i:s',time())
                 ];
         if(!$id){

           $info = Db::name('smsverification')->insert($data);
         }else{
           $info =  Db::name('smsverification')->where(['user_id'=>$user_id])->update($data);
         }
          if($info){
            $data = ['code'=>200,'message'=>'SUCCESS'];
            return $data;
          }else{
            $data = ['code'=>400,'message'=>'失败'];
            return $data;
          }

       }
    }


}